<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="遇见与成长 - 图腾客户管理系统 - 用户列表">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
    <link rel="stylesheet" href="/apps/css/mui.css">
</head>
<body>
    <header class="d-flex align-items-center bg-custom-color p-3 justify-content-between">
        <button id="backButton" class="btn btn-primary rounded-circle me-3" style="background-color: white;" onclick="history.back();">
            <i class="fas fa-arrow-left custom-color"></i>
        </button>
        <span class="title-text text-white fs-5">{{excerpt}}</span>
        <button id="createButton" class="btn btn-primary rounded-circle ms-3" style="background-color: white;" onclick="createRecord();">
            <i class="fas fa-plus custom-color"></i>
        </button>
    </header>
    <div class="container">
        <div class="content">
            <div class="row">
                <div class="col-12">
                    <p>{{{description}}}</p>
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered">
                             <thead class="table-light">
                                <tr>
                                    {{#each fields}}
                                    <th scope="col" class="cell-content">{{this}}</th>
                                    {{/each}}
                                </tr>
                            </thead>
                            <tbody>
                                {{#each rows}}
                                <tr data-id="{{this.id}}" onclick="showDataModal('{{this.id}}');">
                                    {{#each this}}
                                    <td class="cell-content">{{this}}</td>
                                    {{/each}}
                                </tr>
                                {{/each}}
                            </tbody>

                            {{!--
                            <thead class="table-light">
                                <tr>
                                    <th scope="col" class="cell-content" style="width:50px">UID</th>
                                    <th scope="col" class="cell-content">联系</th>
                                    <th scope="col" class="cell-content">Basic</th>
                                </tr>
                            </thead>
                            <tbody>
                                {{#each rows}}
                                <tr data-id="{{this.uid}}" onclick="showUserInfo('{{this.uid}}');">
                                    <td class="cell-content">
                                        <small>#{{this.uid}}</small><br>
                                        <img src="{{{this.avatar}}}" class="rounded-circle" alt="User Image" width="50px">
                                    </td>
                                    <td class="cell-content" width="20%">
                                        <small>{{{this.basic}}}</small>
                                    </td>
                                    <td class="cell-content">
                                        <small style="color:#ff7f50">{{{this.events}}}</small>
                                        <small>{{{this.overview}}}</small>
                                        <small style="color:#c1c1c1">{{{this.updated_at}}}</small>
                                    </td>
                                </tr>
                                {{/each}}
                            </tbody>
                            --}}
                        </table>
                </div>
            </div>
        </div>
    </div>

    <nav aria-label="Page navigation" class="pagination-container">
        <button id="homeButton" class="btn btn-primary position-absolute top-0 start-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="window.location.href='https://totemlife.cn/apps/crm/';">
            <i class="fas fa-home" style="color:white;"></i>
        </button>
        <button id="formButton" class="btn btn-primary position-absolute top-0 end-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="showQueryForm();">
            <i class="fas fa-search" style="color: white;"></i>
        </button>
        <ul class="pagination">
            {{{paginator}}}
        </ul>
    </nav>

</div>

<div class="modal fade" id="queryModal" tabindex="-1" aria-labelledby="queryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="queryModalLabel">设置统计参数</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="queryForm" onsubmit="submitQueryForm()">
                <div class="modal-body">
                    <div class="row">
                        <div class="col">
                            <div class="mb-2">
                                <label for="begin" class="form-label">创建日期起始</label>
                                <input type="date" class="form-control" id="begin" name="begin" value="{{begin}}">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="end" class="form-label">创建日期截至</label>
                                <input type="date" class="form-control" id="end" name="end" value="{{end}}">
                            </div>
                        </div>
                    </div>
                    <!-- ${repCondition} ${oidCondition} ${uidCondition} ${cidCondition} ${uinfoCondition} ${minfoCondition} ${tinfoCondition} -->
                    <div class="row">
                        <div class="col">
                            <div class="mb-2">
                                <label for="uid" class="form-label">用户</label>
                                <input type="text" class="form-control" id="uid" name="uid" value="{{uid}}" placeholder="uid">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="urep" class="form-label">代表</label>
                                <input type="text" class="form-control" id="urep" name="urep" value="{{urep}}" placeholder="urep">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="cid" class="form-label">渠道</label>
                                <input type="text" class="form-control" id="cid" name="cid" value="{{cid}}" placeholder="cid">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="crep" class="form-label">CREP</label>
                                <input type="text" class="form-control" id="crep" name="crep" value="{{crep}}" placeholder="crep">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="aid" class="form-label">客服</label>
                                <input type="text" class="form-control" id="aid" name="aid" value="{{aid}}" placeholder="aid">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <div class="mb-2">
                                <label for="uinfo" class="form-label">用户信息</label>
                                <input type="text" class="form-control" id="uinfo" name="uinfo" value="{{uinfo}}" placeholder="可搜用户名、手机号、地址">
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="mb-2">
                                <label for="pinfo" class="form-label">档案信息</label>
                                <input type="text" class="form-control" id="pinfo" name="pinfo" value="{{pinfo}}" placeholder="可搜索用户档案及跟进信息">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <div class="mb-2">
                                <label for="minfo" class="form-label">用户备注</label>
                                <input type="text" class="form-control" id="minfo" name="minfo" value="{{minfo}}" placeholder="搜索客服备注的用户信息">
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="mb-2">
                                <label for="ginfo" class="form-label">历史购买</label>
                                <input type="text" class="form-control" id="ginfo" name="ginfo" value="{{ginfo}}" placeholder="可搜索TTYS、DDT等商品代码">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer" id="clientModalFooter">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭查询</button>
                        <button type="submit" class="btn btn-primary">查询数据</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="userProfileModal" tabindex="-1" aria-labelledby="userProfileModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userProfileModalLabel">用户档案信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="closeUserProfilesModal"></button>
            </div>
            <div class="modal-body">
                <!-- 输入最新跟进记录的表单 -->
                <form id="newRecordForm">
                    <div class="row">
                        <div class="col-4">
                        <div class="mb-2">
                            <label for="view" class="form-label">录入类型</label>
                            <select class="form-select" id="type" name="type">
                                <option value="crm-direct_report">直接获取</option>
                                <option value="crm-proxy_report">间接获取</option>
                            </select>
                        </div>
                        </div>
                        <div class="col-4">
                        <div class="mb-2">
                            <label for="view" class="form-label">信息分类</label>
                            <select class="form-select" id="confidentiality" name="confidentiality">
                                <option value="Confidential">内部查阅</option>
                                <option value="Unclassified">公开信息</option>
                                <option value="Secret">需要审批</option>
                                <option value="TopSecret">保密信息</option>
                            </select>
                        </div>
                        </div>
                        <div class="col-4">
                        <div class="mb-2">
                            <label for="attachment" class="form-label">附件</label>
                            <input type="file" class="form-control" id="attachment" multiple onchange="uploadFiles(this.files)">
                        </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="mb-2">
                            <label for="uploadedFiles" class="form-label">已传附件</label>
                            <ul id="uploadedFilesList" class="list-unstyled"></ul>
                        </div>
                    </div>
                    <div class="row">
                        <div class="mb-2">
                            <label for="memo" class="form-label">输入最新的跟进记录</label>
                            <textarea class="form-control" id="memo" rows="3"></textarea>
                        </div>
                    </div>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="closeUserProfilesModal2">关闭弹窗</button>
                    <button type="button" class="btn btn-primary" onclick="addUserProfile()">添加记录</button>
                </form>
                <!-- 在这里显示用户档案记录 -->
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>来源</th>
                                <th>内容</th>
                                <!-- 添加其他需要显示的列 -->
                            </tr>
                        </thead>
                        <tbody id="userProfileRecords"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<footer class="footer" style="text-align: center;">
    <div class="row">
        <div class="text-muted">&nbsp;</div>
        <div class="text-muted">&nbsp;</div>
        <div class="text-muted">&copy;2023 图腾生命医学</div>
        <div class="text-muted">我们为人类免疫事业而奉献</div>
    </div>
</footer>

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="/apps/js/bootstrap.bundle.min.js"></script>
<script src="/apps/js/crm-hbs-utils.js"></script>
<script src="/apps/js/wx-client-dom.js"></script>
<script>
    const totemUID = parseInt("{{totemUID}}") || 0;
    let attachmentUrls = []; // 在适当的地方定义
    let selectedFileNames = [];

    function createRecord() {
        if ( totemUID != 1 ) {
            alert('灰度测试 - 只有部分用户可以使用啊！');
            return;
        }
        const url = `https://totemlife.cn/apps/crm/create-sales-lead`;
        window.location.href = url;
    }
    function clearUserProfilesInput() {
            // 清空表单内容
            const formInputs = document.querySelectorAll('#userProfileModal input, #userProfileModal textarea');
            formInputs.forEach(input => { input.value = ''; });
            attachmentUrls = []; // 在适当的地方定义
            selectedFileNames = [];
            // 获取已上传文件列表容器
            const uploadedFilesList = document.getElementById('uploadedFilesList');
            // 清空已上传文件列表
            uploadedFilesList.innerHTML = '';
    };

    // 获取关闭模态框按钮元素
    const closeButton = document.getElementById('closeUserProfilesModal');
    const closeButton2 = document.getElementById('closeUserProfilesModal2');
    // 为关闭按钮添加点击事件监听器
    closeButton.addEventListener('click', function() {
        clearUserProfilesInput();
    });
    closeButton2.addEventListener('click', function() {
        clearUserProfilesInput();
    });

    async function addUserProfile(uid) {
        const memo = document.getElementById('memo').value;
        const type = document.getElementById('type').value;
        const confidentiality = document.getElementById('confidentiality').value;
        if (!memo && memo == '' && memo.length < 5 ){
            alert('请提交有意义的跟进记录');
            return false;
        };
        const attachment = document.getElementById('attachment').files;
            try {
                const response = await fetch('/apps/api/user-profile', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ uid, memo, type, attachmentUrls, confidentiality })
                });
                if (response.ok) {
                    const userProfileRecords = document.getElementById('userProfileRecords');
                    const title = `${type} user#${uid}`;
                    const current = (new Date()).toLocaleString('en-US').replace(/\//g, '-');

                    let attachments_link = '';
                    attachmentUrls.forEach((url, index) => {
                        const fileName = selectedFileNames[index]; // 获取对应文件的本地名称
                        attachments_link += `<span><a href="#" onclick="openFile('${url}', '${fileName}')">${fileName} </a></span>`;
                    });

                    const recordHTML = `
                        <tr>
                            <td><small>${title}<br><span style='color:#c1c1c1'>${current}</span></small></td>
                            <td><small>${memo}<br>${attachments_link}</small></td>
                            <!-- 根据需要添加其他列 -->
                        </tr>
                        `;
                    // 显示插入新记录
                    userProfileRecords.insertAdjacentHTML('afterbegin', recordHTML);
                    clearUserProfilesInput();
                } else {
                    // 提示错误
                    console.error('Failed to add user profile');
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }
        async function uploadFiles(files, code='assifiedddUserProfile') {
            const formData = new FormData();
            formData.append('uid', totemUID);
            formData.append('code', code);
            let fileName = 'UNTITLED';
            Array.from(files).forEach((file) => {
                formData.append('file', file);
                fileName = file.name;
            });
        const uploadUrl = 'https://mall.totembio.cn/api/uploadMtaFile'; // 后端文件传接口地址
            const response = await fetch(uploadUrl, {
                method: 'POST',
                body: formData,
            });
            if (response.ok) {
                const responseData = await response.json();
                const uploadedSrc = responseData?.data?.src;
                attachmentUrls.push(uploadedSrc); // 将上传成功的附件链接保存到 attachmentUrls 数组中
                selectedFileNames.push(fileName); // 记录所选文件的名称
                showUploadedFilesList();
            } else {
                alert('文件上传失败！');
            }
        }

        function showUploadedFilesList() {
            // 获取已上传文件列表容器
            const uploadedFilesList = document.getElementById('uploadedFilesList');
            // 清空已上传文件列表
            uploadedFilesList.innerHTML = '';
            // 填充已上传文件链接到列表中
            attachmentUrls.forEach((url, index) => {
                const listItem = document.createElement('li');
                const fileName = selectedFileNames[index]; // 获取对应文件的本地名称
                listItem.innerHTML = `
                    <span><a href="#" onclick="openFile('${url}', '${fileName}')">${fileName}</a></span>
                    <span style="color: red; cursor: pointer;" onclick="removeAttachment(${index})">删除附件</span>
                `;
                uploadedFilesList.appendChild(listItem);
            });
        }

        function openFile(url, fileName) {
            const fileURL = `${url}`; // 构建完整的文件 URL
            const newWindow = window.open(fileURL, '_blank');
            if (newWindow) {
                newWindow.document.write(`<html><head><title>${fileName}</title></head><body><h1>${fileName}</h1><iframe src="${fileURL}" style="width:100%; height:100vh;"></iframe></body></html>`);
            } else {
                alert('请允许弹出窗口以查看文件');
            }
        }

        // 新增移除已上传文件链接的函数
        function removeAttachment(index) {
            // 从 attachmentUrls 数组中移除指定索引的链接
            attachmentUrls.splice(index, 1);
            selectedFileNames.splice(index, 1);
            showUploadedFilesList();
        }

        function showUserInfo(uid){
            const url = `https://totemlife.cn/apps/crm/disclose-user-info?uid=${uid}`;
            window.location.href = url;
        };

        function showUserProfiles(uid) {

            const modalTitle = document.querySelector('#userProfileModal .modal-title');
            modalTitle.textContent = `#${uid}的用户档案信息`;
            // 清空表单内容
            const formInputs = document.querySelectorAll('#userProfileModal input, #userProfileModal textarea');
            formInputs.forEach(input => { input.value = ''; });
            attachmentUrls = []; // 在适当的地方定义
            selectedFileNames = [];

            fetch(`/apps/api/user-profiles?uid=${uid}`)
                .then(response => response.json())
                .then(data => {
                    const userProfiles = data.userProfiles;
                    // 获取模态框和记录的容器
                    const modal = new bootstrap.Modal(document.getElementById('userProfileModal'));
                    const userProfileRecords = document.getElementById('userProfileRecords');
                    // 清空容器内容
                    userProfileRecords.innerHTML = '';
                    // 填充用户档案记录到容器中
                    userProfiles.forEach(record => {
                        const recordHTML = `
                            <tr>
                                <td><small>${record.type} ${record.atype}#${record.aid}<br><span style='color:#c1c1c1'>${record.created_at}</span></small></td>
                                <td>
                                    <small>
                                        ${record.memo}<br>
                                        ${record.attachments_link}
                                    </small>
                                </td>
                                <!-- 根据需要添加其他列 -->
                            </tr>
                        `;
                        userProfileRecords.insertAdjacentHTML('beforeend', recordHTML);
                    });
                    // 添加记录按钮
                    const addButton = document.querySelector('#userProfileModal #newRecordForm button.btn-primary');
                    addButton.setAttribute('onclick', `addUserProfile('${uid}')`);
                    modal.show();
                    // 显示模态框
                })
                .catch(error => {
                    console.error('Error fetching user profile:', error);
                    // 处理错误情况
                });
        }

        function showQueryForm() {
            const modal = new bootstrap.Modal(document.getElementById('queryModal'));
            modal.show();
        }
        function submitQueryForm() {
            const queryParams = new URLSearchParams();
            const paramsToCheck = ['begin', 'end', 'uid', 'urep', 'cid', 'crep', 'aid',  'uinfo', 'pinfo', 'minfo', 'ginfo'];
            for (const param of paramsToCheck) {
                const value = encodeURIComponent(document.getElementById(param).value);
                if (value && value !== '') queryParams.append(param, value);
            }
            const url = `https://totemlife.cn/apps/crm/users?${queryParams.toString()}`;
            window.location.href = url;
        }
    </script>
</body>
</html>
